﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _06_手动同步事件_自动同步事件
{
    public partial class Form1 : Form
    {

        //手动同步事件=>构造函数传入参数的作用,是否设置为不阻塞的状态 False:阻塞 True:不阻塞
        ManualResetEvent manul = new ManualResetEvent(false);

        //自动同步事件=>构造函数设置阻塞状态  False;阻塞 True:不阻塞
        AutoResetEvent auto = new AutoResetEvent(false);

        public Form1()
        {
            InitializeComponent();
            //取消跨线程访问检查
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 显示窗体完毕后，启动线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Shown(object sender, EventArgs e)
        {
            //实例化启动线程-1
            Thread thread = new Thread(new ThreadStart(DoWork));
            thread.IsBackground= true;
            thread.Start();
            //实例化启动线程-2
            new Thread(() =>
            {
                for (int i = 1; i <= 100; i++)
                {
                    //使用自动同步事件=>阻塞当前线程
                    auto.WaitOne();
                    //叠加
                    this.progressBar2.Value= i;
                    //线程休眠
                    Thread.Sleep(200);
                }
            }) { IsBackground = true }.Start();
        }

        public void DoWork()
        {
            for (int i = 0; i <= 100; i++)
            {
                //使用手动同步事件=>作用是阻塞当前线程(也可以解除对当前线程的阻塞)
                manul.WaitOne();
                //更新进度条
                this.progressBar1.Value = i;
                //休眠
                Thread.Sleep(200);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            manul.Set();//解除阻塞
        }

        private void button2_Click(object sender, EventArgs e)
        {
            manul.Reset();//恢复阻塞
        }

        private void button3_Click(object sender, EventArgs e)
        {
            auto.Set();//解除阻塞
        }
    }
}
